<template>
    <div class="wrap pageCommonContainer">
        <div class="pageBox h100h medium" loginstatus="true" v-loading="loading">
            <div class="topicBox h100h" data-theme="light">
                <div class="topiccontent h100h">
                    <div class="topiccontentL" :class="showLeft ? 'show' : 'hide'">
                        <template v-if="showLeft">
                            <div class="hideOrshowL" @click="toggle">&lt;</div>
                        </template>
                        <template v-else>
                            <div class="hideOrshowL" @click="toggle">></div>
                        </template>

                        <div class="content" v-if="showLeft">
                            <div class="chapterName"><i class="iconQuestionBank"></i>{{ questionMeta.name }}
                            </div>
                            <div class="topicL_ListBox">
                                <div class="topicL_List">
                                    <div class="topicL_ListWap">
                                        <template v-for="(item, index) in anotherMyAnswerCards" :key="index">
                                            <el-collapse class="" v-model="collapse">
                                                <el-collapse-item disabled name="name"
                                                    :title="questionTypeMap[item[0].questionType]">
                                                    <div @click="changeCurrent(item1.num - 1)" class="cardList"
                                                        :class="{ biaoji: item1.noted, isactive: item1.current, yida: item1.answerStatus == 'done'  }"
                                                        v-for="(item1, index1) in item" :key="index1">
                                                        {{ item1.num }}
                                                    </div>
                                                </el-collapse-item>
                                            </el-collapse>
                                        </template>
                                    </div>
                                </div>
                                <div class="topicL_ListBottom">
                                    <div class="list">
                                        <div class="cardList isactive"></div>
                                        <div>当前</div>
                                    </div>
                                    <div class="list">
                                        <div class="cardList yida"></div>
                                        <div>已答</div>
                                    </div>
                                    <div class="list">
                                        <div class="cardList omission"></div>
                                        <div>未答</div>
                                    </div>
                                    <div class="list">
                                        <div class="cardList biaoji"></div>
                                        <div>标记</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="topiccontentR h100h">
                        <div class="tiListBox h100h">
                            <div class="questionType" v-if="currentQuestion">
                                <p class="left">{{ questionTypeMap[currentQuestion['firstType']] }}</p>
                                <el-countdown v-if="props.mode == modes[0]" :value="examTime"></el-countdown>
                                <p class="right"><span class="questionCount">{{ currentIndex + 1 }}/{{
                                    questionList.length }}</span> <span class="line"></span>
                                </p>
                            </div>
                            <div class="questionList h100h">
                                <div class="questionContent h100h flex" v-if="currentQuestion">
                                    <div class="questionBox h100s">
                                        <div>
                                            <div class="questionTitle"><span class="questionNum">{{ currentIndex + 1
                                            }}</span>

                                                <span v-html="currentQuestion.stem[0]['vl']"></span>
                                            </div>
                                            <div class="questionOptionMap">
                                                <template v-if="currentQuestion['firstType'] == 1">
                                                    <el-radio-group class="my-radio-group"
                                                        v-model="myAnswerCards[currentIndex].answer" @change="changeRadio">
                                                        <el-radio v-for="(item, index) in currentQuestion['quOption']"
                                                            :key="index" :label="item.option" class="my-checkbox">
                                                            <div class="my-option">
                                                                <span class="icon">{{ item.option }}</span>
                                                                <span style="margin-left:20px"
                                                                    v-html="item.content[0]['vl']">

                                                                </span>
                                                            </div>
                                                        </el-radio>
                                                    </el-radio-group>
                                                </template>
                                                <template
                                                    v-else-if="currentQuestion['firstType'] == 2 || currentQuestion['firstType'] == 7">

                                                    <el-checkbox-group v-model="myAnswerCards[currentIndex].answer"
                                                        @change="changeCheckbox">
                                                        <el-checkbox class="my-checkbox"
                                                            v-for="(item, index) in currentQuestion['quOption']" :key="index"
                                                            :label="item.option">
                                                            <div class="my-option">
                                                                <span class="icon">{{
                                                                    item.option }}</span>
                                                                <span style="margin-left:20px"
                                                                    v-html="item.content[0]['vl']">
                                                                </span>
                                                            </div>

                                                        </el-checkbox>
                                                    </el-checkbox-group>

                                                </template>
                                                <template v-else-if="currentQuestion['firstType'] == 3">
                                                    <el-radio-group class="my-radio-group"
                                                        v-model="myAnswerCards[currentIndex].answer" @change="changeRadio">
                                                        <el-radio v-for="(item, index) in currentQuestion['quOption']"
                                                            :key="index" :label="item.option" class="my-checkbox"
                                                            :class="{ right: myAnswerCards[currentIndex].answerStatus == 'done' && currentOptionsStatus.right == item.option, wrong: myAnswerCards[currentIndex].answerStatus == 'done' && currentOptionsStatus.wrong == item.option }">
                                                            <div class="my-option">
                                                                <span class="icon">{{ item.option }}</span>
                                                                <span style="margin-left:20px">
                                                                    {{ item.option == 0 ? '错' : '对' }}
                                                                </span>
                                                            </div>
                                                        </el-radio>
                                                    </el-radio-group>
                                                </template>
                                                <template v-else-if="currentQuestion['firstType'] == 4">
                                                    <el-input v-for="(item, index) in currentQuestion['quOption']"
                                                        v-model="myAnswerCards[currentIndex]['answer' + index]"
                                                        @change="(str) => fillChange(str, index)">
                                                    </el-input>
                                                </template>
                                                <template v-else-if="currentQuestion['firstType'] == 5">
                                                    <el-input class="textarea-input" type="textarea" v-model="myAnswerCards[currentIndex].answer"
                                                        placeholder="请输入答案" style="width:700px"
                                                        @change="textareaChange"></el-input>
                                                </template>
                                            </div>
                                            <div class="btnLookAnalysis"
                                                v-if="props.mode == modes[1] && myAnswerCards[currentIndex].answerStatus != 'done'"
                                                @click="submitThis">确定</div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                            <div class="jiexiqu h100h"
                                v-if="props.mode == modes[1] && myAnswerCards[currentIndex].answerStatus == 'done'">
                                <div class="commonTitle" style="padding-left:20px">解析</div>
                                <div class="jiexiBox h100s">


                                    <template v-if="myAnswerCards[currentIndex].questionType != 5">
                                        <div class="common_title">
                                            <div class="common_border"></div>
                                            <div class="common_title">我的答案</div>
                                        </div>
                                        <div class="commontext"><span class="rescolor"
                                                v-html="currentMyAnswerText(myAnswerCards[currentIndex])">
                                            </span></div>
                                        <div class="common_title">
                                            <div class="common_border"></div>
                                            <div class="common_title">参考答案</div>
                                        </div>
                                        <div class="commontext mycolor"
                                            v-html="currentAnalyseText(myAnswerCards[currentIndex])">
                                        </div>
                                    </template>



                                    <div class="common_title">
                                        <div class="common_border"></div>
                                        <div class="common_title">解析</div>
                                    </div>
                                    <div class="commontext" v-html="currentQuestion.answerDesc[0].vl">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="topicBottomWrap">
                <div class="topicBottom">
                    <div class="topicBottomL">
                        <div class="outBtn" @click="saveAndExit">退出并保存</div>
                        <div class="saveBtn" @click="submit">提交</div>
                    </div>
                    <div class="topicBottomR">
                        <div class="topicBottomR_btn">
                            <template v-if="currentIndex != undefined && myAnswerCards[currentIndex].noted">
                                <div class="biaojiBtn biaojiBtnH" data-theme="light" @click="toggleNote"><i></i>取消收藏
                                </div>
                            </template>
                            <template v-else>
                                <div class="biaojiBtn biaojiBtnH not-noted" data-theme="light" @click="toggleNote">
                                    <i></i>收藏本题
                                </div>
                            </template>
                            <div class="prevTi" v-if="currentIndex > 0" @click="preQuestion"><i></i>上一题</div>
                            <div class="nextTi" v-if="currentIndex < myAnswerCards.length - 1" @click="nextQuestion">
                                下一题<i></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>


<script setup>
// 考试模式：有倒计时，无确认键检查对错，有结果页
// 练习模式：无倒计时，有确认键检查对错，解析
import practiseTopicApis from '@/apis/practiseTopic.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import listApis from '@/apis/list';
import questionApis from '@/apis/question';
import useLocalStore from '@/stores/local';
import { computed } from 'vue';
import { getCurrentInstance } from 'vue'

import { encrypt } from '@/utils/jsencrypt.js'
// import { AES_CBC_ENCRYPT } from '@/utils/jsencrypt'
// import config from '@/config/index.js'
import { onBeforeRouteLeave } from 'vue-router';


let exitAction = 'url'
const showLeft = ref(true)
const loading = ref(false)
// 状态显示权重 :当前>标记>(已答|未答)
const questionStatusList = [{ current: '当前', done: '已答', notDone: '未答', noted: '标记' }]
// 单选多选答案与参考答案对比，其中多选答案排序后循环判断所有或者转字符串对比
// answerStatus:'done','notDone'
const myAnswerCards = ref([]);
const anotherMyAnswerCards = ref([]);
const questionList = ref([])
const questionTypeMap = ref({})
const questionMeta = ref({})
const collapse = ref(['name'])
const localStore = useLocalStore()
const route = useRoute()
const router = useRouter()
let lastId = null
const modes = ['exam', 'practice', 'chapterPractice', 'randomExam']
const questionTypeMap1 = {
    1: 'singleChoice',
    2: 'multipleChoice',
    3: 'judgment',
    4: 'fill',
    5: 'text',
    6: 'combination',
    7: 'indefiniteMultipleChoice',
}
const props = defineProps({
    mode: {
        type: String,
        default: ''
    },
})


// ---
const currentIndex = computed(() => {
    for (let i in myAnswerCards.value) {
        if (myAnswerCards.value[i].current == true) {
            return Number(i)
        }
    }
})


// ---
const currentQuestion = computed(() => {
    return questionList.value[currentIndex.value];
})
// ---
const currentOptionsStatus = computed(() => {
    if (currentIndex.value != undefined) {
        const currentCard = myAnswerCards.value[currentIndex.value];
        if (currentCard.answerStatus == 'done' && props.mode == modes[1]) {
            // 锁定答案与正确答案格式相同
            let answer = currentCard.lockAnswer;
            let rightAnswer = currentCard.rightAnswer;

            // 判断题选项0、1
            switch (currentCard.questionType) {
                case 1:
                case 3:
                    if (answer == rightAnswer) {
                        return {
                            right: answer,
                            wrong: ''
                        }
                    } else {
                        return {
                            right: rightAnswer,
                            wrong: answer
                        }
                    }
                    break;
                // 多选、不定项
                case 2:
                case 7:
                    answer.sort((a, b) => {
                        return a.charCodeAt(0) - b.charCodeAt(0)
                    });
                    answer = answer.toString();
                    if (answer == rightAnswer.toString()) {
                        return {
                            right: rightAnswer,
                            wrong: [],
                            noSelected: []
                        }
                    } else {
                        let arr1 = answer.split(',')
                        let arr2 = [...rightAnswer]
                        let right = []
                        let wrong = []
                        let noSelected = []
                        for (let i = 0; i < arr1.length; i++) {
                            let findIndex = arr2.findIndex((e) => {
                                return e == arr1[i]
                            })
                            // 正确且选中
                            if (findIndex > -1) {
                                right.push(arr1[i])
                                arr2.splice(findIndex, 1)
                            } else {
                                wrong.push(arr1[i])
                            }
                        }
                        noSelected.push(...arr2)
                        return {
                            right,
                            wrong,
                            noSelected
                        }
                    }
                    break;
                case 4:

                    break;
                default:
                    break;
            }

        }
        return {}
    }
})
// ---
function answerFill(item, answerx) {

    if (item.record) {
        if (item.firstType == 4) {
            let array = item.record.as.split(' ')
            for (let i = 0; i < array.length; i++) {
                answerx['answer' + i] = array[i]
            }
            return item.record.as
        } else {
            if (item.record.as != null) {
                return JSON.parse(item.record.as)
            }
        }
    } else {
        if (item.firstType == 4) {
            for (let i = 0; i < item.quOption.length; i++) {
                answerx['answer' + i] = ''
            }
            return ''
        }
        // 多选不定项是数组形式的
        const answer = [2, 7].includes(questionType) ? [] : '';
        return answer
    }
}
function changeCheckbox(arr) {
    lastId = currentQuestion.value.id
    if (props.mode == modes[0]||props.mode == modes[3]) {
        myAnswerCards.value[currentIndex.value].answerStatus = 'done'
    }


}
// ---
function changeCurrent(index) {
    myAnswerCards.value[currentIndex.value].current = false;
    myAnswerCards.value[index].current = true;
}
function changeRadio(val) {
    lastId = currentQuestion.value.id
    if (props.mode == modes[0]||props.mode == modes[3]) {
        myAnswerCards.value[currentIndex.value].answerStatus = 'done'
    }

}
function currentMyAnswerText(myCard) {
    // 1: 'singleChoice',
    // 2: 'multipleChoice',
    // 3: 'judgment',
    // 4: 'fill',
    // 5: 'text',
    // 6: 'combination',
    // 7: 'indefiniteMultipleChoice',

    switch (myCard.questionType) {
        case 1:
            return myCard.answer
        case 3:
            return myCard.answer == 0 ? '错' : '对'
        case 4:
            let arr = []
            for (let i = 0; i < myCard.length; i++) {
                arr.push(`${i + 1}.${myCard['answer' + i]}`)
            }
            return arr.join('<br/>');
        case 5:
            return ''
        case 2:
        case 7:
            return myCard.answer.join(' ')
        default:

    }
}
function currentAnalyseText(myCard) {
    switch (myCard.questionType) {
        case 1:
        case 5:
            return myCard.rightAnswer
        case 3:
            return myCard.rightAnswer == 0 ? '错' : '对'
        case 4:
            return myCard.rightAnswer.split(' ').map((e, i) => {
                return `${i + 1}.${e}`
            }).join('<br/>');

        case 2:
        case 7:
            return myCard.rightAnswer.join(' ')
        default:
    }
}
// ---
function fillChange(val, index) {
    lastId = currentQuestion.value.id
    if (val.length > 0) {
        myAnswerCards.value[currentIndex.value].answerStatus = 'done'
    } else {
        for (let i = 0; i < myAnswerCards.value[currentIndex.value].length; i++) {
            if (myAnswerCards.value[currentIndex.value]['answer' + i]) {
                myAnswerCards.value[currentIndex.value].answerStatus = 'done'
                return
            }
        }
        myAnswerCards.value[currentIndex.value].answerStatus = 'notDone'
    }
}
// 后端规定的答案格式
function getAnswer(cardItem) {
    let as;
    switch (cardItem.questionType) {
        // 填空
        case 4:
            let arr = [];
            for (let i = 0; i < cardItem.length; i++) {
                arr.push(cardItem['answer' + i].trim())
            }
            as = arr.join(' ');
            break;
        // 多选/不定项
        case 2:
        case 7:
            as = JSON.stringify(cardItem.lockAnswer || cardItem.answer);
            break;
        // 单选、判断、解答
        case 1:
        case 3:
        case 5:
            as = cardItem.lockAnswer || cardItem.answer;
            break;
        default:
            break;
    }
    return as;
}
async function init() {
    let practiceModel, questionCollectionTrue;
    if (props.mode == modes[0]) {
        practiceModel = false
        questionCollectionTrue = false
    } else if (props.mode == modes[1]) {
        practiceModel = true
        questionCollectionTrue = true
    } else if (props.mode == modes[2]) {
        questionCollectionTrue = true
        if (route.query.restart) {
            await questionApis.cleanCollectRecords(route.query.id, {
                data: {
                    ...localStore.userSelectedIdsMap,
                    recordsType: 'chapter',
                    haveCollect: true,
                    id: route.query.id
                }
            })
        }
    }



    let res1;
    if (!route.query.recordId) {
        if (props.mode == modes[0] || props.mode == modes[1]) {
            try {
                res1 = await paperApis.generateRecords(null, {
                    params: {
                        ...localStore.userSelectedIdsMap,
                        paperId: route.query.id,
                        // recordsId:detail.value.id,
                        columnId: route.query.columnId,
                        result: false,
                        // strict:false,
                        practiceModel
                    }, headers: {
                        'content-type': 'application/x-www-form-urlencoded'
                    }
                })
            } catch (err) {
                if (err.code == 104) {
                    exitAction = 'force'
                    ElMessage('3秒后返回')
                    setTimeout(() => {
                        router.go(-1)
                    }, 3000)

                    return
                }
            }
        }
    } else {
        res1 = ({
            data: {
                id: route.query.recordId,
                examTime: Number(route.query.examTime),
                qcount: Number(route.query.qcount),
            }
        })
    }
    let questionCollectionId;
    if (props.mode == modes[0] || props.mode == modes[1]) {
        questionCollectionId = res1.data.id
    } else if (props.mode == modes[2]) {
        questionCollectionId = route.query.id
    }

    const res = await listApis.questionCollection(encrypt(JSON.stringify({
        collectionType: 'paper',
        industryCode: localStore.userSelectedIdsMap.industryCode,
        examId: localStore.userSelectedIdsMap.examId,
        categoryId: localStore.userSelectedIdsMap.categoryId,
        columnId: route.query.columnId,
        id: questionCollectionId,
        true: questionCollectionTrue
    })));
    lastId = res.data.lastId
    let now = Date.now()


    const { id, name } = res.data
    questionMeta.value = { id, name, collectId: route.query.id }
    if (props.mode == modes[0]) {
        examTime.value = now + res1.data.examTime * 60 * 1000
        questionMeta.value.qcount = res1.data.qcount
    }
    let array = []
    let questionArray = []
    let anotherMyAnswerCardsCopy = []
    let num = 0
    const content = res.data.content
    let thisCurrent = false
    for (let i in content) {
        anotherMyAnswerCardsCopy[i] = []
        let newArr = []
        const qs = content[i].qs;
        if (qs && qs.length > 0) {
            const questionType = qs[0].firstType
            questionTypeMap.value[questionType] = qs[0].type
            for (let j in qs) {
                num++
                let answer, lockAnswer;
                let answerx = {}
                answer = answerFill(qs[j], answerx)
                if (props.mode == modes[1] || props.mode == modes[2]) {
                    if (typeof answer == 'string')
                        lockAnswer = answer;
                    else if (answer == null) return;
                    else
                        lockAnswer = JSON.parse(JSON.stringify(answer));
                }


                let current = false;
                if (lastId && lastId == qs[j].id) {
                    current = true;
                    thisCurrent = true
                }
                newArr.push({
                    num,
                    id: qs[j].id,
                    questionType,
                    answer,
                    lockAnswer,
                    current,
                    answerStatus: qs[j].record ? 'done' : 'notDone',
                    isTrue: qs[j].record ? qs[j].record.rt : false,
                    // qs[j].record.rt?
                    // analyse: qs[j].answerDesc,
                    note: '',
                    noted: qs[j].collect,
                    rightAnswer: qs[j].rightAnswer || '',
                    time: 0,
                    notedTime: qs[j].collect ? 1 : 0,
                    savedBefore: qs[j].record ? true : false,
                    length: qs[j]['quOption'].length,
                    ...answerx

                });
                questionArray.push(qs[j])
            }
        }


        array.push(...newArr)
        anotherMyAnswerCardsCopy[i].push(...newArr)
    }
    questionList.value = questionArray
    myAnswerCards.value = array
    anotherMyAnswerCards.value = anotherMyAnswerCardsCopy


    if (!thisCurrent)
        myAnswerCards.value[0].current = true;
}

// ---
function nextQuestion() {
    let current = currentIndex.value
    if (current >= myAnswerCards.value.length - 1) {
        return
    }
    changeCurrent(current + 1)
}




onBeforeRouteLeave((to, from, next) => {
    if (exitAction == 'url') {
        submitBeforeLeave().finally(_ => {
            next()
        })
    } else {
        next()
    }
})


function preQuestion() {

    let current = currentIndex.value
    if (current <= 0) {
        return
    }
    changeCurrent(current - 1)
}
async function randomInit() {
    if (!db.isOpen()) {
        db.open()
    }
    db.on('ready', () => {
        db.exam.get(route.query.id).then(response => {
            const res = response


            lastId = res.data.lastId
            const { id, name } = res.data
            questionMeta.value = { id, name, qcount: 10 }
            let array = []
            let questionArray = []
            let anotherMyAnswerCardsCopy = []
            let num = 0
            const content = res.data.content
            for (let i in content) {

                anotherMyAnswerCardsCopy[i] = []
                let newArr = []
                const qs = content[i].qs;
                if (qs && qs.length > 0) {
                    const questionType = qs[0].firstType
                    questionTypeMap.value[questionType] = qs[0].type
                    for (let j in qs) {
                        num++
                        let answer, lockAnswer;
                        let answerx = {}
                        answer = answerFill(qs[j], answerx)
                        if (props.mode == modes[1] || props.mode == modes[2]) {
                            if (typeof answer == 'string')
                                lockAnswer = answer;
                            else if (answer == null) return;
                            else
                                lockAnswer = JSON.parse(JSON.stringify(answer));
                        }


                        newArr.push({
                            num,
                            id: qs[j].id,
                            questionType,
                            answer,
                            lockAnswer,
                            current: false,
                            answerStatus: qs[j].record ? 'done' : 'notDone',
                            isTrue: qs[j].record ? qs[j].record.rt : false,
                            // qs[j].record.rt?
                            // analyse: qs[j].answerDesc,
                            note: '',
                            noted: qs[j].collect,
                            rightAnswer: qs[j].rightAnswer || '',
                            time: 0,
                            notedTime: qs[j].collect ? 1 : 0,
                            savedBefore: qs[j].record ? true : false,
                            length: qs[j]['quOption'].length,
                            ...answerx
                        });
                        questionArray.push(qs[j])
                    }
                }


                array.push(...newArr)
                anotherMyAnswerCardsCopy[i].push(...newArr)
            }
            questionList.value = questionArray
            myAnswerCards.value = array
            anotherMyAnswerCards.value = anotherMyAnswerCardsCopy

            myAnswerCards.value[0].current = true
        })
    })
}
function saveAndExit() {
    exitAction = 'click'
    if (props.mode == modes[1]) {
        router.go(-1)
    } else if (props.mode == modes[0] || props.mode == modes[2]) {
        if (questionList.value.length == 0) {
            return router.go(-1)
        }
        submitBeforeLeave().finally(res => {
            router.go(-1)
        })
    }
}
//???
function submit() {
    if (loading.value) return;
    exitAction = 'click';
    loading.value = true;
    // 保存请求
    // 权重lockAnswer>answer，循环一次(lockAnswer/answer)
    // 所有答案填完才能提交
    const commonData = Object.assign({
        recordsType: 'paperRecordPaperLibrary',
        recordsId: questionMeta.value.id,
        chapterId: route.query.id,
        seconds: Number.parseInt((Date.now() - now) / 1000),
        cn: questionMeta.value.name,
        totalCount: questionMeta.value.qcount,
        ...signAndTimestamp(),
        imageCheck: false

    }, localStore.userSelectedIdsMap);


    // data1已做，data2收藏，data3错题
    const data = {};



    for (let i in myAnswerCards.value) {
        const cardItem = myAnswerCards.value[i]
        const questionItem = questionList.value[i]

        if (myAnswerCards.value[i].answerStatus == 'done') {
            let as=getAnswer(cardItem)
            data[cardItem.id] = {
                qid: questionItem.id,
                qt: questionItem.firstType,
                tr: '',
                as,
                sn: questionItem.sign,
                t: cardItem.time,
                rt: cardItem.isTrue,
                newDo: !cardItem.savedBefore,
                asb: questionItem.answerBase64,
                st: questionItem.stem
            }
        }
    }

    return questionApis.submitPaper({
        ...commonData,
        lastId,
        data
    }).then(res => {


        localStore.setExamResult(res.data)
        // 跳转结果页
        if (res.data) {
            router.push({
                path: '/question/paper/result',
                query: {
                    id: res.data.paperRecords.id
                }
            })
        }
    }).finally(_ => {
        loading.value = false;
    })
}
function submitBeforeLeave() {
    let recordsType, ct;
    if (props.mode == modes[0]) {
        recordsType = 'paperRecordPaperLibrary'
        ct = 'paperRecordPaperLibrary'
    } else if (props.mode == modes[1]) {
        recordsType = 'paperRecordChapterPractice'
        ct = 'paperRecordChapterPractice'
    } else if (props.mode == modes[2]) {
        recordsType = 'chapter'
        ct = 'chapter'
    } else if (props.mode == modes[3]) {
        recordsType = 'paperRecordPaperLibrary'
        ct = 'paperRecordPaperLibrary'
    }


    if (loading.value) return;
    loading.value = true;
    // 保存请求
    // 权重lockAnswer>answer，循环一次(lockAnswer/answer)
    // 所有答案填完才能提交
    const commonData = Object.assign({
        recordsType,
        recordsId: questionMeta.value.id,
        chapterId: route.query.id,
        seconds: Number.parseInt((Date.now() - now) / 1000),
        cn: questionMeta.value.name,
        totalCount: questionMeta.value.qcount,
    }, localStore.userSelectedIdsMap);
    // data1已做，data2收藏，data3错题

    const data = {}, data1 = {}, data2 = {}, removeIds = [], cdata = {}, data3 = {};
    let dc = 0, ec = 0, cc = 0;
    for (let i in myAnswerCards.value) {
        const cardItem = myAnswerCards.value[i]
        const questionItem = questionList.value[i]
        if (myAnswerCards.value[i].answerStatus == 'done') {

            // ???
            const as = getAnswer(cardItem)
            data[cardItem.id] = {
                as,
                t: cardItem.time,
                rt: false,
            }


            if (!myAnswerCards.value[i].isTrue) {
                data3[cardItem.id] = {
                    qid: questionItem.id,
                    qt: questionItem.firstType,
                    tr: '',
                    as: cardItem.lockAnswer.length > 0 ? cardItem.lockAnswer : cardItem.answer,
                    sn: questionItem.sign,
                    ct: 'paperRecordChapterPractice',
                    cid: route.query.id,
                    cn: route.query.name,
                    t: cardItem.time,
                    st: questionItem.stem
                }
                ec++;
            }
            dc++;
            data1[cardItem.id] = {
                qid: questionItem.id,
                qt: questionItem.firstType,
                tr: '',
                as: cardItem.lockAnswer,
                sn: questionItem.sign,
                t: cardItem.time,
                rt: cardItem.isTrue,
                newDo: !cardItem.savedBefore,
                asb: questionItem.answerBase64
            }
        }
        if (cardItem.noted) {
            cc++;
            cdata[cardItem.id] = cardItem.notedTime == 1 ? 0 : cardItem.notedTime
            data2[cardItem.id] = {
                qid: questionItem.id,
                qt: questionItem.firstType,
                tr: '',
                as: cardItem.lockAnswer.length > 0 ? cardItem.lockAnswer : cardItem.answer,
                sn: questionItem.sign,
                ct: 'chapter',
                cid: route.query.id,
                cn: route.query.name,
                t: cardItem.notedTime == 1 ? 0 : cardItem.notedTime,
                st: questionItem.stem
            }
        }
        else {
            if (cardItem.notedTime < 0) {
                removeIds.push(cardItem.id)
            }
        }
    }
    let promiiseArr = []
    if (props.mode == modes[2]) {
        dc -= Number(route.query.dc || 0)
        ec -= Number(route.query.ec || 0)
        cc -= Number(route.query.cc || 0)
    }
    // 没做就不保存了
    if (!lastId) {
        loading.value = false;
        return Promise.resolve();
    } else {
        if (props.mode == modes[1] || props.mode == modes[2]) {
            promiiseArr.push(questionApis.pushChapter(Object.assign({
                collectName: questionMeta.value.name,
                data: data1, lastId, totalCount: myAnswerCards.value.length
            }, commonData)),)
        }
    }

    promiiseArr.push(questionApis.pushCollect(Object.assign({ collectName: questionMeta.value.name, removeIds }, commonData, {
        cdata,
        data: data2
    })))

    if (props.mode == modes[0]) {
        promiiseArr.push(questionApis.savePaper({
            ...commonData,
            lastId,
            data
        }))
        return Promise.all(promiiseArr).finally(_ => {
            loading.value = false;
        })
    } else if (props.mode == modes[1] || props.mode == modes[2]) {
        promiiseArr.push(questionApis.saveChapter(Object.assign({ data: { dc, ec, cc, } }, commonData)),
            questionApis.pushError({
                ...commonData,
                collectName: questionMeta.value.name,
                data: data3,
            }))

        return Promise.all(promiiseArr).finally(_ => {
            loading.value = false;
        })
    }
}
async function submitThis() {

    // 提交本题答案请求
    const currentCard = myAnswerCards.value[currentIndex.value]
    if (currentCard.answerStatus == 'done') {
        return;
    }
    const as = getAnswer(currentCard)
    if (as == null || as == '') {
        ElMessage('请选择答案')
        return;
    }


    if (props.mode == modes[1]) {
        currentCard.lockAnswer = currentCard.answer
    }



    const requestObj = {
        ...localStore.userSelectedIdsMap,
        columnId: route.query.columnId,
        qid: currentQuestion.value.id,
        type: questionTypeMap1[currentQuestion.value.firstType],
        // type: currentQuestion.value.firstType,
        collectId: questionMeta.value.id,
        as,
        answer: currentQuestion.value.answerBase64,
    }
    const res = await questionApis.questionCheck(requestObj)
    currentCard.rightAnswer = res.data.as;
    currentCard.time = new Date().getTime();

    currentCard.answerStatus = 'done';
    // 正确
    if (res.data.rt) {
        currentCard.isTrue = true
    } else {
        currentCard.isTrue = false
    }
    lastId = currentQuestion.value.id
}
function textareaChange(str) {
    if (str.length > 0) {
        lastId = currentQuestion.value.id
        myAnswerCards.value[currentIndex.value].answerStatus = 'done'
    } else {
        myAnswerCards.value[currentIndex.value].answerStatus = 'notDone'
    }
}
function toggle() {
    showLeft.value = !showLeft.value
}

function toggleNote() {
    let recordsType, ct;
    if (props.mode == modes[0]) {
        ct = recordsType = 'paperRecordPaperLibrary'
    } else if (props.mode == modes[1]) {
        ct = recordsType = 'paperRecordChapterPractice'
    } else if (props.mode == modes[2]) {
        ct = recordsType = 'chapter'
    } else if (props.mode == modes[3]) {
        ct = recordsType = 'paperRecordChapterPractice'
    }

    if (!myAnswerCards.value[currentIndex.value].noted) {
        questionApis.collectQuestion({
            ...localStore.userSelectedIdsMap,
            columnId: route.query.columnId,
            qid: currentQuestion.value.id,
            true: true,
            recordsType,
            data: {
                qt: currentQuestion.value.firstType,
                tr: '',
                cid: route.query.id,
                ct,
                cn: route.query.name,
                as: myAnswerCards.value[currentIndex.value].answer,
                sn: currentQuestion.value.sign,
                t: new Date().getTime(),
                st: currentQuestion.value.stem
            }
        }).then(res => {
            if (res.data == true) {
                myAnswerCards.value[currentIndex.value].noted = true
                myAnswerCards.value[currentIndex.value].notedTime = new Date().getTime()
            }
            // questionApis.paperRecordsCollect(localStore.userSelectedIdsMap)
        })
    } else {
        questionApis.delCollect({
            ...localStore.userSelectedIdsMap,
            qid: currentQuestion.value.id,
        }).then(res => {
            if (res.success == true) {
                myAnswerCards.value[currentIndex.value].noted = false
                myAnswerCards.value[currentIndex.value].notedTime = -1
            }
        })
    }
}
init()











</script>